

from common import config


# 数据库连接 pip install PyMySQL
import pymysql 
# from common import sys_log
from utils.log import logger
import time

class MyDB:
    def __init__(self) -> None:
        self.__connect_mysql_db()
        

    # 连接数据库
    def __connect_mysql_db(self):
        try:
            db_config = config['db']

            self.cnn = pymysql.connect(host=db_config['host'],  
                                user=db_config['user'],  
                                password=db_config['password'],  
                                database=db_config['database'],  
                                charset='utf8mb4',  # 使用utf8mb4编码，以支持emoji等特殊字符  
                                cursorclass=pymysql.cursors.DictCursor)  # 使用字典类型的游标
            
            print('数据库连接成功！！')
            self.cursor = self.cnn.cursor()
            return True
        except Exception as e:
            print(f"数据库连接失败：{e}")
            logger.error(f"连接失败：{e}")
            return False

    # 重连
    def _reConn(self, num=28800, stime=3):  
        _number = 0
        _status = True
        while _status and _number <= num:
            try:
                self.cnn.ping(reconnect=True)  # cping 校验连接是否异常
                _status = False
            except:
                if self.__connect_mysql_db() == True:  # 重新连接,成功退出
                    _status = False
                    break
                _number += 1
                time.sleep(stime)  # 连接不成功,休眠3秒钟,继续循环
    def find_first(self,sql): 
        try:
            self._reConn()                 
            self.cursor.execute(sql)  
            res = self.cursor.fetchone()
            self.close()
            return  res
        except Exception as e:
            print(f'find_first error:{str(e)}')
            self.__connect_mysql_db()
            self.find_first(sql)
            
    def find(self ,sql):
        try:
            self._reConn() 
            self.cursor.execute(sql)  
            res = self.cursor.fetchall()
            self.close()
            return  res
        except Exception as e:
            print(f'find error:{str(e)}')
            self.__connect_mysql_db()
            self.find(sql)
        

    def insertOrUpdate(self,sql):  
        try:
            is_success=True
            self._reConn() 
        
            #执行插入sql
            self.cursor.execute(sql)
            # 提交到数据库执行
            self.cnn.commit()                
        except Exception as e:
            logger.log(f'db error : 更新数据库错误：{e}')
            # 如果发生错误则回滚
            is_success = False
            self.cnn.rollback()
        # 关闭数据库连接
        self.close()
        return is_success

    def close(self):
        self.cnn.close()